<template>
  <BasicModal
    v-bind="$attrs"
    :destroyOnClose="true"
    :minHeight="550"
    :width="650"
    @register="registerModal"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <Tabs v-model:activeKey="activeKey" @change="onTabChange">
      <TabPane key="1" :tab="t('routes.demo.workFlow.startFlow.property')">
        <Form :labelCol="{ span: 6 }" :wrapperCol="{ span: 16, offset: 1 }">
          <FormItem :label="t('routes.demo.workFlow.startFlow.propertySet.name')">
            <Input
              v-model:value="lcName"
              :placeholder="t('routes.demo.workFlow.startFlow.propertySet.namePlaceholder')"
            />
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.propertySet.code')">
            <Input
              v-model:value="lcCode"
              :placeholder="t('routes.demo.workFlow.startFlow.propertySet.codePlaceholder')"
              readOnly
            >
              <template #addonAfter>
                <Tooltip
                  :title="t('routes.demo.workFlow.startFlow.propertySet.selectFlowTemplate')"
                >
                  <a-button @click="handleSelectFlow">...</a-button>
                </Tooltip>
              </template>
            </Input>
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.propertySet.startTime')">
            <Input
              v-model:value="lcStarTime"
              :placeholder="t('routes.demo.workFlow.startFlow.propertySet.startTimePlaceholder')"
              readOnly
            />
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.propertySet.principal')">
            <Input
              v-model:value="lcCharge"
              :placeholder="t('routes.demo.workFlow.startFlow.propertySet.principalPlaceholder')"
              disabled
            />
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.propertySet.stepSelect')">
            <Checkbox v-model:checked="lcChecked">{{
              t('routes.demo.workFlow.startFlow.propertySet.allowStepSelect')
            }}</Checkbox>
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.propertySet.backMethod')">
            <RadioGroup v-model:value="lcBack">
              <Radio value="0">{{
                t('routes.demo.workFlow.startFlow.propertySet.backMethodCustom')
              }}</Radio>
              <Radio value="1">{{
                t('routes.demo.workFlow.startFlow.propertySet.backMethodSelect')
              }}</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.propertySet.overdueTime')">
            <Row>
              <Col :span="8">
                <Input
                  v-model:value="lcDay"
                  :placeholder="
                    t('routes.demo.workFlow.startFlow.propertySet.overdueTimePlaceholder')
                  "
                />
              </Col>
              <Col :span="4" style="text-align: center">
                <span>{{ t('component.time.days') }}</span>
              </Col>
              <Col :span="8">
                <Input
                  v-model:value="lcHour"
                  :placeholder="
                    t('routes.demo.workFlow.startFlow.propertySet.overdueTimePlaceholder')
                  "
                />
              </Col>
              <Col :span="4" style="text-align: center">
                <span>{{ t('component.time.hours') }}</span>
              </Col>
            </Row>
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.propertySet.overdueMessage')">
            <Select
              v-model:value="lcMessage"
              :placeholder="
                t('routes.demo.workFlow.startFlow.propertySet.overdueMessagePlaceholder')
              "
            >
              <SelectOption v-for="item in userList" :key="item.id" :value="item.id">{{
                item.name
              }}</SelectOption>
            </Select>
          </FormItem>
        </Form>
      </TabPane>
      <TabPane key="2" :tab="t('routes.demo.workFlow.startFlow.step')">
        <BasicTable @register="registerTable" :data-source="stepList">
          <!-- 负责人处理方式 -->
          <template #process="{ text: process }">
            <span>{{
              process === 7
                ? t('routes.demo.workFlow.flowModelPage.selectPrincipal')
                : t('routes.demo.workFlow.flowModelPage.selectPrincipalInTemplate')
            }}</span>
          </template>
          <!-- 超期消息处理方式 -->
          <template #msgOverTimeHandWay="{ text: msgOverTimeHandWay }">
            <span>{{
              msgOverTimeHandWay === '1'
                ? t('routes.demo.workFlow.way3')
                : t('routes.demo.workFlow.way4')
            }}</span>
          </template>
          <!-- 完成消息处理方式 -->
          <template #msgFinishWay="{ text: msgFinishWay }">
            <span>{{
              msgFinishWay === '1' ? t('routes.demo.workFlow.way3') : t('routes.demo.workFlow.way4')
            }}</span>
          </template>
        </BasicTable>

        <Form :model="lcbjform" :labelCol="{ span: 4 }" :wrapperCol="{ span: 18, offset: 1 }">
          <FormItem :label="t('routes.demo.workFlow.startFlow.stepSet.name')">
            <Input
              v-model:value="lcbjform.name"
              :placeholder="t('routes.demo.workFlow.startFlow.stepSet.namePlaceholder')"
              readonly
              :disabled="currentSelectStep.process === 7 && currentSelectStep.isfirst"
            >
              <template #suffix>
                <Icon icon="ion:ios-close-outline" @click="clearName" />
              </template>
              <template #addonAfter>
                <a-button
                  type="primary"
                  @click="handleAdjust"
                  :disabled="currentSelectStep.process === 7 && currentSelectStep.isfirst"
                  >{{ t('routes.demo.workFlow.startFlow.stepSet.adjustStepPrincipal') }}</a-button
                >
              </template>
            </Input>
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.stepSet.overdueTime')">
            <Row>
              <Col :span="8">
                <Input
                  v-model:value="lcbjform.day"
                  :placeholder="t('routes.demo.workFlow.startFlow.stepSet.overdueTimePlaceholder')"
                  :disabled="currentSelectStep.argument === '1'"
                />
              </Col>
              <Col :span="4" style="text-align: center">
                <span>{{ t('component.time.days') }}</span>
              </Col>
              <Col :span="8">
                <Input
                  v-model:value="lcbjform.hour"
                  :placeholder="t('routes.demo.workFlow.startFlow.stepSet.overdueTimePlaceholder')"
                  :disabled="currentSelectStep.argument === '1'"
                />
              </Col>
              <Col :span="4" style="text-align: center">
                <span>{{ t('component.time.hours') }}</span>
              </Col>
            </Row>
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.stepSet.workDescription')">
            <Textarea v-model:value="lcbjform.workDesc" />
          </FormItem>
          <FormItem
            :label="t('routes.demo.workFlow.startFlow.stepSet.stepTable.overdueMessageReceiver')"
          >
            <Select
              v-model:value="lcbjform.expireInfo"
              :placeholder="t('routes.demo.workFlow.startFlow.stepSet.adjustMessageReceiver')"
            >
              <SelectOption v-for="item in userList" :key="item.id" :value="item.id">{{
                item.name
              }}</SelectOption>
            </Select>
          </FormItem>
          <FormItem
            :label="t('routes.demo.workFlow.startFlow.stepSet.stepTable.finishMessageReceiver')"
          >
            <Select
              v-model:value="lcbjform.completeInfo"
              :placeholder="t('routes.demo.workFlow.startFlow.stepSet.adjustMessageReceiver')"
            >
              <SelectOption v-for="item in userList" :key="item.id" :value="item.id">{{
                item.name
              }}</SelectOption>
            </Select>
          </FormItem>
        </Form>
      </TabPane>
      <TabPane key="3" :tab="t('routes.demo.workFlow.startFlow.object')">
        <BasicTable @register="registerObjTable" :dataSource="objList">
          <template #toolbar>
            <a-button type="primary" @click="addDocument">
              {{ t('routes.demo.workFlow.startFlow.addDocument') }}
            </a-button>
            <a-button type="primary" @click="addForm">
              {{ t('routes.demo.workFlow.startFlow.addForm') }}
            </a-button>
          </template>
        </BasicTable>
      </TabPane>
      <TabPane key="4" :tab="t('routes.demo.workFlow.startFlow.referenceDocument')">
        <BasicTable @register="registerDocTable" :dataSource="referenceDocList">
          <template #toolbar>
            <a-button type="primary" @click="addReferenceDoc"> {{ t('common.add') }} </a-button>
          </template>
          <template #action="{ record }">
            <TableAction
              :actions="[
                {
                  icon: 'ion:ios-eye',
                  label: t('common.view'),
                  onClick: handleView.bind(null, record),
                },
                {
                  icon: 'ant-design:delete-outlined',
                  color: 'error',
                  label: t('common.delete'),
                  onClick: handleDelete.bind(null, record),
                },
                {
                  icon: 'ion:download-outline',
                  label: t('common.download'),
                  onClick: handleDownload.bind(null, record),
                },
              ]"
            />
          </template>
        </BasicTable>
      </TabPane>
    </Tabs>
  </BasicModal>
  <!-- 选择流程窗口 -->
  <BasicModal
    v-bind="$attrs"
    :destroyOnClose="true"
    :minHeight="200"
    :width="1000"
    @register="registerSelectFlow"
    @ok="handleSelectionSubmit"
  >
    <BasicTable
      @register="registerSelectionTable"
      :dataSource="wkfList"
      :rowSelection="{
        type: 'radio',
        selectedRowKeys: wkfselectedRowKeys,
        onChange: wkfSelectChange,
      }"
    />
  </BasicModal>
  <!-- 调整步骤负责人窗口 -->
  <BasicModal
    v-bind="$attrs"
    :destroyOnClose="true"
    :minHeight="200"
    :width="500"
    @register="registerAdjust"
    @ok="handleAdjustSubmit"
    @cancel="handleAdjustCancel"
  >
    <InputSearch
      :placeholder="t('routes.demo.workFlow.initiateFlowPage.search')"
      style="width: 200px; margin-bottom: 10px"
      :allowClear="true"
      @change="changeSearch"
      @search="psnSearch"
    />
    <BasicTable @register="registerAdjustTable" :data-source="psnSelectDatat" />
  </BasicModal>
  <!-- 选择表单类型窗口 -->
  <BasicModal
    v-bind="$attrs"
    :destroyOnClose="true"
    :minHeight="50"
    :width="300"
    @register="registerSelectFormType"
    @ok="SelectFormTypeSuccess"
    @cancel="SelectFormTypeCancel"
  >
    <span> {{ t('routes.demo.workFlow.startFlow.formType') }}</span>
    <Select v-model:value="formType" style="width: 200px">
      <SelectOption v-for="item in formTypeList" :key="item.id" :value="item.id">{{
        item.name
      }}</SelectOption>
    </Select>
  </BasicModal>
  <!-- 新增图档 -->
  <selectDocModal @register="registerSelectDocModal" @success="handleSelectDocModalSuccess" />
  <!-- 新增表单渲染弹窗 -->
  <formModal @register="registerFormModal" @success="handleFormModalSuccess" />
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import {
    getFlowStepColumns,
    getFlowObjColumns,
    getSelectionColumns,
    getAdjustColumns,
    getFlowDocColumns,
  } from './flowData';
  import Icon from '/@/components/Icon';
  import {
    Tabs,
    TabPane,
    Form,
    FormItem,
    Input,
    Tooltip,
    Checkbox,
    Radio,
    Row,
    Col,
    InputSearch,
    Select,
    SelectOption,
  } from 'ant-design-vue';

  import moment from 'moment';
  import { useUserStore } from '/@/store/modules/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Getallpersondto } from '/@/api/demo/system';
  import {
    checkInFlowApi,
    getCodeNameApi,
    getInfoTipsApi,
    getStepApi,
    getCommonFlowApi,
    getCheckInApi,
    getNewFlowApi,
    getParticipantApi,
    getTemplateList,
    getTemplateListByType,
    GetallWfsTypedata,
    AddAllWorkflowReleaseTwd,
  } from '/@/api/demo/flow';

  import { getBorrowFlowTemplate } from '/@/api/demo/knowledge';
  import { getFileTypeAndFlowTypeTemplateList } from '/@/api/demo/document';
  import selectDocModal from '/@/views/demo/documentManager/components/selectDocModal.vue';
  import formModal from '/@/views/components/formModal.vue';

  const { t } = useI18n();
  const Textarea = Input.TextArea;
  const RadioGroup = Radio.Group;

  const useCommonStore = useUserStore();
  const { createMessage } = useMessage();
  const activeKey = ref('1');
  const lcName = ref<any>('');
  const lcCode = ref('');
  const lcStarTime = ref('');
  const lcCharge = ref('');
  const lcChecked = ref(false);
  const lcBack = ref('0');
  const lcDay = ref('');
  const lcHour = ref('');
  const currentSelectWkf = ref<any>({});
  const lcMessage = ref('');

  const currentSelectStep = ref<any>({});
  const someInfos = ref<any>({
    projectid: '',
    projectName: '',
    taskName: '',
  });
  const currentSelectFile = ref<any>({});
  const wkfList = ref<any>([]);
  const wkfInfos = ref<any>({});
  const wkfselectedRowKeys = ref<any>([]);
  const stepList = ref<any>([]);
  const stepMessage = ref<any>('');
  const personList = ref<any>([]);
  const psnSelectDatat = ref<any>([]);
  const selectedRowKeys = ref<any>([]);
  const objList = ref<any>([]);
  const lcbjform = ref<any>({
    name: '',
    day: '',
    hour: '',
    workdesc: '',
    expireinfo: '',
    completeinfo: '',
  });
  const currentIndex2 = ref<number>(0);
  const stepCharge = ref<any>({});
  const currentIndex3 = ref('');
  const formsId = ref<any>('');
  const submitType = ref<any>('');
  const userList = ref<any>([]);
  const referenceDocList = ref<any>([]);
  const formType = ref<string>('');
  const formTypeList = ref<any>([]);

  const [registerModal, { closeModal: closeFlowModal, openModal: openFlowModal }] = useModal();
  const [registerSelectFlow, { openModal: openSelectFlowModal }] = useModal();
  const [registerAdjust, { openModal: openAdjustModal }] = useModal();
  const [
    registerSelectFormType,
    { openModal: openSelectFormTypeModal, closeModal: closeSelectFormTypeModal },
  ] = useModal();

  // 步骤表格
  const [registerTable] = useTable({
    columns: getFlowStepColumns(),
    showIndexColumn: false,
    showTableSetting: false,
    bordered: true,
    pagination: false,
    canResize: false,
    rowKey: 'shortId',
    customRow: (record, index) => {
      return {
        onClick: () => {
          // 打开调整弹窗
          currentSelectStep.value = record;
          if (index === 0) {
            currentSelectStep.value.isfirst = true;
          } else {
            currentSelectStep.value.isfirst = false;
          }
          lcbjform.value.name = currentSelectStep.value.actor;
          lcbjform.value.workdesc = currentSelectStep.value.description;
          currentIndex2.value = index;
        },
      };
    },
    //改变 当负责人代号为空的那一行字体颜色为红色，负责人代号不为空字体颜色为黑色，选中当前行背景色改为蓝色
    rowClassName: (record: any, index) => {
      let classStr = '';
      let actor = record.actor.replace(/\s*/, '');
      if (!actor) {
        if (record.unSelected == '1') {
          classStr += 'rowClassSelected';
        } else {
          classStr += 'rowClass2';
        }
      }
      if (index === currentIndex2.value) {
        classStr += ' rowClass';
      }
      return classStr;
    },
  });

  // 对象表格
  const [registerObjTable] = useTable({
    columns: getFlowObjColumns(),
    showIndexColumn: false,
    showTableSetting: false,
    bordered: true,
    pagination: false,
    rowKey: 'id',
    canResize: true,
    scroll: { y: 300 },
  });

  // 参考文档
  const [registerDocTable] = useTable({
    columns: getFlowDocColumns(),
    showIndexColumn: false,
    showTableSetting: false,
    bordered: true,
    pagination: false,
    rowKey: 'id',
    canResize: true,
    scroll: { y: 300 },
    actionColumn: {
      width: 200,
      fixed: 'right',
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  // 选择流程表格选中事件
  const wkfSelectChange = (selectedRowKeys) => {
    wkfselectedRowKeys.value = selectedRowKeys;
    currentSelectWkf.value = wkfList.value.find((o) => o.id === wkfselectedRowKeys.value[0]);
    stepList.value = [];
  };

  async function handleSelectionSubmit() {
    if (wkfselectedRowKeys.value.length === 1) {
      lcCode.value = wkfselectedRowKeys.value[0];
      lcBack.value = currentSelectWkf.value.status.toString();
      if (currentSelectWkf.value.status === 0) {
        lcChecked.value = false;
      } else {
        lcChecked.value = true;
      }
      getInfoTipsApi(lcCode.value).then((res) => {
        if (res === null) {
          lcMessage.value = '';
        } else {
          lcMessage.value = res.msgInceptor;
        }
      });

      // 查询步骤信息
      getStepApi(wkfselectedRowKeys.value[0]).then((res) => {
        if (!res.liststdto || !Array.isArray(res.liststdto) || res.liststdto.length <= 1) {
          return createMessage.error(t('routes.demo.workFlow.initiateFlowPage.noStep'));
        }

        stepList.value = res.liststdto;
        currentSelectStep.value = stepList.value[0];
        stepMessage.value = res.message;
        if (stepMessage.value) {
          createMessage.info(res.message);
        }
        // 流程第一步默认为流程发起人
        if (!stepList.value[0].actor?.trim()) {
          stepList.value[0].actor = `@psn@${useCommonStore.userInfo?.userId}`;
        }

        stepList.value.forEach((item) => {
          if (item.actor?.trim()) {
            let id = item.actor.split('@').pop();
            let obj = personList.value.find((o) => o.id == id);
            if (obj) {
              item.name = obj.name;
            }
          }
        });
      });
    }
    openSelectFlowModal(false);
  }

  // 选择流程表格
  const [registerSelectionTable] = useTable({
    columns: getSelectionColumns(),
    showIndexColumn: false,
    showTableSetting: false,
    bordered: true,
    canResize: false,
    striped: false,
    rowKey: 'id',
  });

  async function handleAdjustSubmit() {
    const newStepList = [...stepList.value];
    if (Object.keys(stepCharge.value).length != 0) {
      let obj = newStepList.find((o) => o.id == currentSelectStep.value.id);
      if (obj != null) {
        obj.actor = '@psn@' + stepCharge.value.id;
        obj.name = stepCharge.value.name;
        lcbjform.value.name = '@psn@' + stepCharge.value.id;
      }
      stepList.value = newStepList;
    }
    handleAdjustCancel();
  }

  async function handleAdjustCancel() {
    stepCharge.value = {};
    psnSelectDatat.value = personList.value;
    openAdjustModal(false);
  }
  const SelectFormTypeSuccess = () => {
    openFormModal(true);
    SelectFormTypeCancel();
  };

  const SelectFormTypeCancel = () => {
    formType.value = '';
    closeSelectFormTypeModal();
  };

  const changeSearch = (e) => {
    if (e.type === 'click') {
      psnSelectDatat.value = personList.value;
    }
  };
  // 流程步骤选择负责人搜索
  const psnSearch = (value) => {
    if (!value) {
      return;
    } else {
      const searchList = personList.value;
      const resData = searchList.filter((o) => o.id.includes(value) || o.name.includes(value));
      psnSelectDatat.value = resData;
      //如果只有1条记录自动选择
      if (psnSelectDatat.value.length == 1) {
        stepCharge.value = psnSelectDatat.value[0];
      }
    }
  };

  // 调整步骤负责人表格
  const [registerAdjustTable] = useTable({
    columns: getAdjustColumns(),
    showIndexColumn: false,
    showTableSetting: false,
    bordered: true,
    canResize: false,
    striped: false,
    rowKey: 'id',
    customRow: (record) => {
      return {
        onClick: () => {
          stepCharge.value = record;
          currentIndex3.value = record.id;
        },
      };
    },
    rowClassName: (record: any) => {
      return record.id === currentIndex3.value ? 'clickRowStyle' : '';
    },
  });

  // 获取参与者，负责人
  getParticipantApi().then((res) => {
    personList.value = res;
    psnSelectDatat.value = personList.value;
  });
  getParticipantApi();

  // 选择流程
  const handleSelectFlow = () => {
    openSelectFlowModal(true);
  };

  // 清除步骤负责人
  const clearName = () => {
    const newStepList = [...stepList.value];
    let obj = newStepList.find((item) => item.id == currentSelectStep.value.id);
    if (obj != null) {
      obj.actor = '';
      obj.name = '';
      lcbjform.value.name = '';
    }
    stepList.value = newStepList;
  };

  // 调整步骤负责人
  async function handleAdjust() {
    openAdjustModal(true);
  }

  // 切换Tab
  const onTabChange = (key) => {
    if (key === 2) {
      if (stepList.value.filter((item) => item.actor === ' ').length === 1) {
        let count = 0;
        for (let i = 0; i < stepList.value.length; i++) {
          if (stepList.value[i].actor === ' ') {
            count++;
          }
        }
        currentIndex2.value = count;
        currentSelectStep.value = stepList.value.filter((item) => item.actor === ' ')[0];
        if (currentIndex2.value == 0) {
          currentSelectStep.value.isfirst = true;
        } else {
          currentSelectStep.value.isfirst = false;
        }
        lcbjform.value.name = currentSelectStep.value.actor;
        lcbjform.value.workdesc = currentSelectStep.value.description;
      } else {
        currentIndex2.value = 0;
        currentSelectStep.value = stepList.value[0];
        if (currentIndex2.value == 0) {
          currentSelectStep.value.isfirst = true;
        } else {
          currentSelectStep.value.isfirst = false;
        }
        lcbjform.value.name = currentSelectStep.value.actor;
        lcbjform.value.workdesc = currentSelectStep.value.description;
      }
    }
  };

  // 流程事件
  // record当前文档信息，type流程类型，keys文档对象id，selectedFiles选中文件，projectid项目id，projectName项目名称，taskName任务名称，formId表单id
  const lcShow = (record, type, keys, selectedFiles, projectid, projectName, taskName, formId) => {
    // 获取人员列表
    Getallpersondto({}).then((res) => {
      userList.value = res;
    });
    submitType.value = type;
    formsId.value = formId;
    someInfos.value = { projectid, projectName, taskName };
    const setCommonFlowData = (name, typeDescription) => {
      lcName.value = name;
      lcStarTime.value = moment(new Date()).format('YYYY年MM月DD日');
      lcCharge.value = `@psn@${useCommonStore.userInfo?.userId}`;
      // 打开流程模态框
      openFlowModal(true, wkfList.value);
      getCodeNameApi(
        typeDescription,
        currentSelectFile.value.filename,
        currentSelectFile.value.version,
      ).then((res) => {
        wkfInfos.value = res; // 获取流程信息
      });
    };

    const handleSteps = () => {
      getStepApi(wkfselectedRowKeys.value[0])
        .then((res) => {
          if (!res || !Array.isArray(res.liststdto) || res.liststdto.length <= 1) {
            return createMessage.error(t('routes.demo.workFlow.initiateFlowPage.noStep'));
          }
          stepList.value = res.liststdto;
          currentSelectStep.value = stepList.value[0];
          stepMessage.value = res.message || '';
          if (stepMessage.value) {
            createMessage.info(stepMessage.value);
          }
          // 流程第一步默认为流程发起人
          // 如果stepList.value[0].actor为空或者为空字符串，则将其赋值为@psn@加上useCommonStore.userInfo?.userId
          if (!stepList.value[0].actor?.trim()) {
            stepList.value[0].actor = `@psn@${useCommonStore.userInfo?.userId}`;
          }
          // 给流程步骤第一步属性赋值
          const newStep = stepList.value.find((o) => o[0].shortId);
          lcbjform.value.day = newStep.day;
          lcbjform.value.hour = newStep.hour;
          lcbjform.value.workdesc = newStep.description;
          lcbjform.value.expireinfo = newStep.overTimeMsgReciver;
          lcbjform.value.completeinfo = newStep.msgFinsihReciver;
          stepList.value.forEach((item) => {
            if (item.actor?.trim()) {
              let id = item.actor.split('@').pop();
              let obj = personList.value.find((o) => o.id == id);
              if (obj) {
                item.name = obj.name;
              }
            }
          });
        })
        .catch(() => {
          createMessage.error('获取步骤失败，请稍后重试');
        });
    };

    const handleSingleFlow = async () => {
      currentSelectFile.value = record;
      objList.value.push(record);
      if (type === 'jr') {
        // 处理流程
        checkInFlowApi(useCommonStore.userInfo?.userId, record.id).then((res) => {
          wkfList.value = res.listwfd;
          lcStarTime.value = moment(new Date()).format('YYYY年MM月DD日');
          lcCharge.value = `@psn@${useCommonStore.userInfo.username}`;
          // 新建流程模板属性初始化赋值
          const newWorkFlow = res.listwfd.find((o) => o.id === res.workflowid);
          if (newWorkFlow) {
            lcChecked.value = newWorkFlow.bzxzSelcted == '1';
            lcBack.value = newWorkFlow.htlcSelected;
            lcDay.value = newWorkFlow.overDays;
            lcHour.value = newWorkFlow.overHours;
            lcMessage.value = newWorkFlow.overTimeReciver;
          }
          getCodeNameApi('检入', record.name, record.version).then((res) => {
            wkfInfos.value = res;
            lcName.value = res.name;
            openFlowModal(true, wkfList.value);
          });
          const workflowId = res.workflowid;
          // 处理步骤
          if (workflowId) {
            const memoryWorkFlowId = localStorage.getItem('memoryWorkFlowId');
            const workflow = wkfList.value.find((o) => o.id === (memoryWorkFlowId || workflowId));
            lcCode.value = workflow?.id || workflowId;
            wkfselectedRowKeys.value = [...wkfselectedRowKeys.value, lcCode.value];
            currentSelectWkf.value = workflow;
            if (wkfselectedRowKeys.value.length === 1) {
              handleSteps();
            }
          }
        });
      } else if (type === 'ty') {
        getCommonFlowApi('', '').then((res) => {
          wkfList.value = res;
          setCommonFlowData('通用流程', '通用');
        });
      } else if (type === 'tz') {
        getFileTypeAndFlowTypeTemplateList(record.type, '通知流程').then((res) => {
          wkfList.value = res;
          setCommonFlowData('通知流程', '通知');
        });
      } else if (type === 'jc') {
        getTemplateList(record.type, '检出流程').then((res) => {
          wkfList.value = res;
          setCommonFlowData('检出流程', '检出');
        });
      } else if (type === 'jy') {
        getBorrowFlowTemplate(record.type).then((res) => {
          wkfList.value = res;
          setCommonFlowData('借阅流程', '借阅');
        });
      } else if (type === 'fz') {
        getTemplateListByType(record.type).then((res) => {
          wkfList.value = res;
          setCommonFlowData('废止流程', '废止');
        });
      } else if (type === 'fb') {
        GetallWfsTypedata('发布流程').then((res) => {
          wkfList.value = res;
          setCommonFlowData('发布流程', '发布');
        });
      }
    };

    const handleBatchFlow = () => {
      currentSelectFile.value = '';
      selectedRowKeys.value = keys;
      objList.value = selectedFiles;
      if (type === 'jr') {
        getCheckInApi(useCommonStore.userInfo?.userId, selectedRowKeys.value.toString()).then(
          (res) => {
            wkfList.value = res;
            if (Array.isArray(res) && res.length > 0) {
              lcCode.value = res[0].name;
              wkfselectedRowKeys.value = [...wkfselectedRowKeys.value, res[0].id];
              currentSelectWkf.value = res[0];
              if (wkfselectedRowKeys.value.length === 1) {
                handleSteps();
              }
            }
            setCommonFlowData('检入流程-多对象', '检入');
          },
        );
      } else if (type === 'fb') {
        GetallWfsTypedata('发布流程').then((res) => {
          wkfList.value = res;
          if (Array.isArray(res) && res.length > 0) {
            lcCode.value = res[0].name;
            wkfselectedRowKeys.value = [...wkfselectedRowKeys.value, res[0].id];
            currentSelectWkf.value = res[0];
            if (wkfselectedRowKeys.value.length === 1) {
              handleSteps();
            }
          }
          setCommonFlowData('发布流程-多对象', '发布');
        });
      }
    };

    if (record) {
      handleSingleFlow();
    } else {
      handleBatchFlow();
    }
  };

  // 新增图档
  const addDocument = () => {
    openSelectDocModal(true, { type: '新建流程对象' });
  };
  // 新增表单
  const addForm = () => {};
  // 新增参考文档
  const addReferenceDoc = () => {
    openSelectFormTypeModal(true);
  };
  // 查看
  const handleView = () => {};
  // 删除
  const handleDelete = () => {};
  // 下载
  const handleDownload = () => {};

  async function handleSubmit() {
    if (currentSelectStep.value.id !== null) {
      const liststi = [];
      const listpdmr = [];
      if (currentSelectFile.value === '') {
        // 多对象发布流程
        if (submitType.value == 'fb') {
          selectedRowKeys.value.forEach((item) => {
            let listpdmrdto = { target: '', version: '' };
            listpdmrdto.target = item.oid;
            listpdmrdto.version = item.version;
            listpdmr.push(listpdmrdto);
          });
        } else {
          // 多对象流程
          selectedRowKeys.value.forEach((item) => {
            let listpdmrdto = { target: '' };
            listpdmrdto.target = item;
            listpdmr.push(listpdmrdto);
          });
        }
      } else {
        if (submitType.value !== 'jy') {
          // 单对象流程
          let listpdmrdto = { target: '', version: '' };
          listpdmrdto.target = currentSelectFile.value.id;
          listpdmrdto.version = currentSelectFile.value.version;
          listpdmr.push(listpdmrdto);
        } else if (submitType.value === 'fb') {
          // 单对象流程
          let listpdmrdto = { target: '', version: '' };
          listpdmrdto.target = currentSelectFile.value.id;
          listpdmrdto.version = currentSelectFile.value.version;
        } else {
          // 单对象流程
          let listpdmrdto = { target: '', version: '' };
          listpdmrdto.target = currentSelectFile.value.id;
          listpdmrdto.version = currentSelectFile.value.version;
          // 表单id
          let formPdm = { target: formsId.value, version: '1' };
          listpdmr.push(formPdm);
          listpdmr.push(listpdmrdto);
        }
      }
      // 查询并列流程
      const binLieList = stepList.value.filter((item) => item.listssdto !== null);

      if (binLieList.length > 0) {
        for (let i = 0; i < binLieList.length; i++) {
          let num = 0;
          for (let j = 0; j < binLieList[i].listssdto.length; j++) {
            let arr = stepList.value.filter(
              (o) => o.actor != ' ' && o.id == binLieList[i].listssdto[j].source,
            );
            if (arr.length > 0) {
              continue;
            } else {
              num++;
            }
          }
          if (num == binLieList[i].listssdto.length) {
            return createMessage.info(t('routes.demo.workFlow.initiateFlowPage.noPrincipal'));
          }
        }
      }
      // 验证整理接口传参数据
      for (let i = 0; i < stepList.value.length; i++) {
        const liststidto = { workflowID: '', actor: '', description: '' };
        liststidto.workflowID = stepList.value[i].id;
        if (
          stepList.value[i].actor === ' ' ||
          stepList.value[i].actor === '' ||
          stepList.value[i].actor === undefined
        ) {
          //未选择负责人
          if (stepList.value[i].unSelected === '0') {
            //未设置流程步骤不选择负责人
            return createMessage.error('步骤：' + stepList.value[i].id + '未指定执行人');
          }
        }
        liststidto.actor = stepList.value[i].actor;
        liststidto.description = stepList.value[i].remark;
        liststi.push(liststidto);
      }

      if (liststi.length > 0 && listpdmr.length > 0) {
        let workflowType = '检入';
        if (submitType.value == 'ty') {
          workflowType = '通用';
        }
        if (submitType.value == 'jy') {
          workflowType = '借阅';
        }
        if (submitType.value == 'jc') {
          workflowType = '检出';
        }
        if (submitType.value == 'fz') {
          workflowType = '废止';
        }
        if (submitType.value == 'tz') {
          workflowType = '通知';
        }
        if (submitType.value == 'fb') {
          workflowType = '发布';
          const fbParams = {
            workflowType: workflowType, // 创建的流程类型
            workflowInstancesid: wkfInfos.value.id, // 流程实例id
            workflowInstancesName: lcName.value, // 流程实例名称
            actor: useCommonStore.userInfo?.userId, // 执行人
            workflow: currentSelectWkf.value.id, // 所选流程类型id
            remark: currentSelectWkf.value.remark, // 流程备注
            creator: useCommonStore.userInfo?.userId, // 创建人
            liststi: liststi, // 流程步骤
            listpdmr: listpdmr, // 流程对象
            rebacksetting: lcBack.value, // 回退设置 0使用模板设置的回退 1选择回退
          };
          AddAllWorkflowReleaseTwd(fbParams).then(() => {
            createMessage.success(t('routes.demo.workFlow.initiateFlowPage.createSuccess'));
            localStorage.setItem('memoryWorkFlowId', currentSelectWkf.value.id);
            handleCancel();
          });
        } else {
          const params = {
            workflowType: workflowType, // 创建的流程类型
            workflowInstancesid: wkfInfos.value.id, // 流程实例id
            workflowInstancesName: lcName.value, // 流程实例名称
            actor: useCommonStore.userInfo?.userId, // 执行人
            workflow: currentSelectWkf.value.id, // 所选流程类型id
            remark: currentSelectWkf.value.remark, // 流程备注
            creator: useCommonStore.userInfo?.userId, // 创建人
            liststi: liststi, // 流程步骤
            listpdmr: listpdmr, // 流程对象
            rebacksetting: lcBack.value, // 回退设置 0使用模板设置的回退 1选择回退
            projectid: someInfos.value.projectid, // 项目id
            projectname: someInfos.value.projectName, // 项目名称
            taskname: someInfos.value.taskName, // 任务名称
            lcStarTime: lcStarTime.value, // 流程开始时间
            lcCharge: lcCharge.value, // 流程负责人
            lcChecked: lcChecked.value, // 步骤选择
            lcDay: lcDay.value, // 超期天数
            lcHour: lcHour.value, // 超期小时
            lcMessage: lcMessage.value, // 超期消息
          };
          getNewFlowApi(params).then(() => {
            createMessage.success(t('routes.demo.workFlow.initiateFlowPage.createSuccess'));
            localStorage.setItem('memoryWorkFlowId', currentSelectWkf.value.id);
            handleCancel();
          });
        }
      } else {
        handleCancel();
      }
    }
  }

  // 取消
  async function handleCancel() {
    closeFlowModal();
    lcName.value = '';
    lcCode.value = '';
    lcStarTime.value = '';
    lcBack.value = '0';
    lcCharge.value = '';
    wkfselectedRowKeys.value = [];
    lcbjform.value.name = '';
    lcbjform.value.workdesc = '';
    currentSelectStep.value = {};
    currentSelectWkf.value = {};
    selectedRowKeys.value = [];
    wkfInfos.value = {};
    objList.value = [];
    referenceDocList.value = [];
    stepList.value = [];
    stepMessage.value = '';
    lcChecked.value = false;
    lcDay.value = '';
    lcHour.value = '';
    lcMessage.value = '';
    activeKey.value = '1';
  }

  const handleSelectDocModalSuccess = (data) => {
    const isExist = objList.value.find((item) => item.id === data.id);
    if (!isExist) {
      objList.value.push(data);
    }
  };

  const handleFormModalSuccess = () => {};

  const [registerSelectDocModal, { openModal: openSelectDocModal }] = useModal();
  const [registerFormModal, { openModal: openFormModal }] = useModal();

  // //暴露lcShow方法
  defineExpose({
    lcShow,
  });
</script>

<style lang="less" scoped>
  ::v-deep(.ant-input-group-addon) {
    background-color: #fff !important;
    border: 0 solid #d9d9d9 !important;
  }

  ::v-deep(.clickRowStyle) {
    background-color: #e6f7ff !important;
  }

  ::v-deep(.rowClassSelected) {
    color: orange !important;
  }

  ::v-deep(.rowClass) {
    background-color: #e6f7ff !important;
  }

  ::v-deep(.rowClass2) {
    color: red !important;
  }
</style>
